<template>
  <div>
    <el-table v-loading="listLoading" :data="list" size="small" :height="height" style="width: 100%; min-height: 360px">
      <el-table-column label="序号" type="index" width="50" />
      <el-table-column label="模块" prop="belongTypeName" sortable align="center" min-width="100" />
      <el-table-column label="类型" align="center" min-width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_random_area_type" :value="row.randomType" />
      </el-table-column>
      <el-table-column label="抽取结果" prop="areaName" min-width="200" />
      <el-table-column label="状态" align="center" min-width="80">
        <el-tag slot-scope="{ row }" size="small" :type="row.isDel ? 'danger' : 'primary'">{{ row.isDel ? '无效' : '有效' }}</el-tag>
      </el-table-column>
      <el-table-column label="无效原因" prop="delReason" show-overflow-tooltip min-width="80" />
      <!-- <el-table-column label="抽取人" prop="creator" align="center" width="100" /> -->
      <el-table-column label="抽取时间" sortable prop="createTime" align="center" width="150" />
      <el-table-column label="操作" fixed="right" align="center" width="80">
        <div slot-scope="{ row }">
          <el-button size="mini" type="text" :loading="row.delLoading" @click="setDel(row)">{{ row.isDel ? '设置有效' : '设置无效' }}</el-button>
        </div>
      </el-table-column>
    </el-table>

    <el-dialog title="抽取结果" :visible.sync="randomResDialog" :close-on-click-modal="false" append-to-body width="1000px" @closed="showCurrentResult = false">
      <el-empty v-if="!showResList.length" />
      <div class="random-res-list" v-else>
        <div v-for="(item1, idx1) in showResList" :key="idx1">
          <div class="title">{{ scoreType2label(item1.belongType) }}</div>
          <div class="item" v-for="(item2, idx2) in item1.list" :key="idx1 + '_' + idx2">
            <div class="subtitle">{{ dict.label.cq_random_area_type[item2.randomType] }}</div>
            <div>
              <el-tag v-for="(item3, idx3) in item2.list" :key="idx1 + '_' + idx2 + '_' + idx3" type="info" style="margin: 0 10px 10px 0">{{ item3.areaName }}</el-tag>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" @click="randomResDialog = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 测区历史抽取记录
import { cqRdcAreaList, cqRdcAreaBatchDelete } from '@/api/projectInspection/courseCheck'
// 以 belongType 和 randomType 逐层归类
const generateCategoryData = data => {
  const obj = {}
  data.map(item => {
    const bt = item.belongType
    const rt = item.randomType
    if (item.isDel || !bt || !rt) return
    !obj[bt] && (obj[bt] = {})
    !obj[bt][rt] && (obj[bt][rt] = [])
    obj[bt][rt].push(item)
  })
  return Object.keys(obj).map(bt => ({
    belongType: bt,
    list: Object.keys(obj[bt]).map(rt => ({ randomType: rt, list: obj[bt][rt] }))
  }))
}

export default {
  props: {
    processType: { type: String, default: '' },
    scoreTypeList: { type: Array, default: () => [] },
    randomId: { type: String, default: '' },
    height: { type: String, default: '360px' }
  },
  dicts: ['cq_random_area_type'],
  data() {
    return {
      listLoading: false,
      list: [],
      randomResDialog: false,
      randomResList: [],
      showCurrentResult: false, // 显示本次结果
      currResList: [] // 本次结果
    }
  },
  computed: {
    showResList() {
      // 弹窗显示的结果列表
      return this.showCurrentResult ? this.currResList : this.randomResList
    }
  },
  methods: {
    reset() {
      this.listLoading = false
      this.list = []
      // this.randomResDialog = false
      this.randomResList = []
    },
    async showResDialog() {
      this.randomResDialog = true
      if (!this.list.length) this.getList()
    },
    async getList(opt = {}) {
      const { currentResultList } = opt
      const { randomId, reset } = this
      if (!randomId) return reset()

      if (currentResultList) {
        this.currResList = generateCategoryData(currentResultList)
        this.showCurrentResult = true
        this.randomResDialog = true
      }

      this.listLoading = true
      const res = await cqRdcAreaList({ randomId }).catch(() => false)
      this.listLoading = false
      if (res === false) return reset()

      const data = res.data || []
      if (!data.length) return reset()

      data.map(i => {
        i.delLoading = false
        i.belongTypeName = this.scoreType2label(i.belongType) || ''
      })
      // console.log('---------', data)
      this.list = data

      this.randomResList = generateCategoryData(data)
    },
    scoreType2label(chkitemCode) {
      let cname = ''
      for (let i = 0; i < this.scoreTypeList.length; i++) {
        if (this.scoreTypeList[i].children && this.scoreTypeList[i].children.length > 0) {
          const clist = this.scoreTypeList[i].children
          clist.forEach(item => {
            if (item.chkitemCode === chkitemCode) {
              cname = item.chkitemName
            }
          })
        } else {
          if (this.scoreTypeList[i].chkitemCode === chkitemCode) {
            cname = this.scoreTypeList[i].chkitemName
          }
        }
      }
      return cname
    },
    async setDel(item) {
      if (item.delLoading) return

      const res1 = await this.$prompt('', '原因', {
        inputPlaceholder: '请输入原因',
        inputValidator: val => !!(val || '').trim(),
        inputErrorMessage: '请输入原因'
      }).catch(action => ({ action }))
      if (res1.action !== 'confirm') return

      const opt = {
        areaId: item.areaId,
        isDel: item.isDel ? 0 : 1,
        delReason: (res1.value || '').trim()
      }
      item.delLoading = true
      const res = await cqRdcAreaBatchDelete([opt]).catch(() => false)
      item.delLoading = false
      if (res === false) return

      this.$message.success('操作成功')
      this.getList()
    }
  }
}
</script>
<style lang="scss" scoped>
.random-res-list {
  max-height: calc(88vh - 200px);
  overflow-y: auto;
  .title {
    background-color: #f8f8f9;
    padding: 10px 15px;
    border-radius: 5px;
    margin-bottom: 10px;
  }
  .item {
    display: flex;
    padding: 5px 15px;
  }
  .subtitle {
    min-width: 60px;
    font-weight: bold;
    line-height: 28px;
    margin-right: 10px;
  }
}
</style>
